package cn.stylefeng.guns.modular.system.service.Myservice;

import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.mapper.AfterIndentMapper;
import cn.stylefeng.guns.modular.system.model.params.AfterIndentCommitParam;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.AfterIndentCheckDTO;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.AfterIndentDTO;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.CheckDTO;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.guns.sys.core.StatusCode.AfterIndentConde;
import cn.stylefeng.guns.sys.core.StatusCode.SalesOrderCode;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.common.SystemConstant;
import cn.stylefeng.guns.sys.core.util.utility.Katrina_CJ_Utils;
import cn.stylefeng.guns.sys.core.util.utility.Order;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 经销商退货或者维修货物接口
 * @Author : xiaofei
 * @Date: 2019/7/10
 */
@Service
public class AfterSalesOrderService extends ServiceImpl<AfterIndentMapper, AfterIndent> {


    @Autowired
    private AfterIndentService afterIndentService;
    @Autowired
    private AfterIndentCheckService afterIndentCheckService;
    @Autowired
    private AfterIndentOrderService afterIndentOrderService;
    @Autowired
    private CheckAfterIndentService checkAfterIndentService;
    @Autowired
    private  AfterIndentCommitService afterIndentCommitService;
    @Autowired
    private  AfterIndentCommitCheckService afterIndentCommitCheckService;
    @Autowired
    private CheckAfterCommitService checkAfterCommitService;
    @Resource
    private TaskService taskService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;

    /**
     * 用户提出售后审核
     * @param afterIndentCommitParam
     */
    public  void afeterIndentCommit(AfterIndentCommitParam afterIndentCommitParam){

        //插入数据到售后审核表中
        List<AfterIndentCheckDTO> afterIndentCheckDTOS = JSON.parseArray(afterIndentCommitParam.getAfterIndent(),AfterIndentCheckDTO.class);

        for (AfterIndentCheckDTO s : afterIndentCheckDTOS) {

            AfterIndentCommit afterIndentCommit = new AfterIndentCommit();
            afterIndentCommit.setReason(s.getReason());
            afterIndentCommit.setTime(new Date());
            afterIndentCommit.setCheckStatus(StatusCode.PENDING.getVal());
            afterIndentCommit.setIndentOrderId(s.getIndentId());
            if ("维修".equals(s.getName())){
                afterIndentCommit.setType(1);
            }else {
                afterIndentCommit.setType(2);
            }
            afterIndentCommit.setUserId(ShiroKit.getUserNotNull().getId());

            //对应流程initUser
            ProcessInstance instance = runtimeService.startProcessInstanceByKey(SystemConstant.afterSale);
            identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() +"");
            afterIndentCommit.setProessInstanceId(instance.getId());
            afterIndentCommitService.save(afterIndentCommit);

            //经销商提交任务
            Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
            taskService.setAssignee(task.getId(),ShiroKit.getUserNotNull().getId() +"");

            //找到刚插入的一条数据
            AfterIndentCommit afterIndentCommitLast = afterIndentCommitService.getOne(new QueryWrapper<AfterIndentCommit>()
                    .lambda().orderByDesc(AfterIndentCommit::getId).last("limit 1"));

            Map<String,Object> map = new HashMap<>();
            map.put("type",afterIndentCommitLast.getType().toString());
            taskService.complete(task.getId(),map);
        }
            //1.插入提交审核表中


    }
    /**
     * 生成售后订单
     * @param afterIndentDTO
     */
    public  void  afterIndentOrder(AfterIndentDTO afterIndentDTO){

        List<AfterIndentDTO> afterIndentDTOS = JSON.parseArray(afterIndentDTO.getAfterIndent(),AfterIndentDTO.class);
        StringBuilder ids = null;
           ids = new StringBuilder();
           for (AfterIndentDTO indentDTO : afterIndentDTOS) {
               //插入到售后采购单
               AfterIndent afterIndent = new AfterIndent();
               BeanUtils.copyProperties(indentDTO,afterIndent);
               if (afterIndentDTO.getType() == AfterIndentConde.SETTING.getVal()) {
                   afterIndent.setType(AfterIndentConde.SETTING.getVal());
               }else {
                   afterIndent.setType(AfterIndentConde.RETURN.getVal());
               }
               afterIndent.setStatus(StatusCode.PENDING.getVal());
               afterIndentService.save(afterIndent);
               //找出最新插入的采购单
               AfterIndent afterIndentLast = afterIndentService.getOne(new QueryWrapper<AfterIndent>()
                       .lambda().orderByDesc(AfterIndent::getId).last("limit 1"));
               ids.append(afterIndent.getId()+",");
           }

           //生成售后单
           AfterIndentOrder afterIndentOrder = new AfterIndentOrder();
           afterIndentOrder.setAfterIndentId(ids.toString());
           afterIndentOrder.setUserId(ShiroKit.getUserNotNull().getId());
           afterIndentOrder.setAfterStatus(StatusCode.PENDING.getVal());
            if (afterIndentDTO.getType() == AfterIndentConde.SETTING.getVal()) {
                afterIndentOrder.setType(AfterIndentConde.SETTING.getVal());
            }else {
                afterIndentOrder.setType(AfterIndentConde.RETURN.getVal());
            }
           //插入上一个售后订单的id
           AfterIndentOrder afterIndentOrderLast = afterIndentOrderService.getOne(new QueryWrapper<AfterIndentOrder>()
           .lambda().orderByDesc(AfterIndentOrder::getId).last("limit 1"));
            if (ToolUtil.isNotEmpty(afterIndentOrderLast)){
                afterIndentOrder.setAfterSaleNum(Katrina_CJ_Utils.createOrderSerial(Order.SH_,afterIndentOrderLast.getId()));
            }else {
                afterIndentOrder.setAfterSaleNum(Katrina_CJ_Utils.createOrderSerial(Order.SH_,(long)1));
            }

           ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.afterSaleOrderv);
           afterIndentOrder.setProcessInstanceId(processInstance.getId());
           afterIndentOrder.setTime(new Date());
           identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() +"");
           afterIndentOrderService.save(afterIndentOrder);

         Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
         taskService.setAssignee(task.getId(),ShiroKit.getUserNotNull().getId() +"");
         taskService.complete(task.getId());
    }


    /**
     * 审核提交审核信息
     * @param checkDTO
     */
    public void checkCommit(CheckDTO checkDTO){

         //更新审核表
        if (checkDTO.getCode() == AfterIndentConde.PASS.getVal()){

            AfterIndentCommitCheck afterIndentCommitCheck = afterIndentCommitCheckService.getById(checkDTO.getId());
            AfterIndentCommit afterIndentCommit = afterIndentCommitService.getById(afterIndentCommitCheck.getAfterIndentCommitId());
            if (afterIndentCommit.getType() == AfterIndentConde.SETTING.getVal()){
                afterIndentCommitCheck.setStatusService(AfterIndentConde.SUCCESS.getVal());
                afterIndentCommitCheck.setCheckUserId(ShiroKit.getUserNotNull().getId());
                afterIndentCommitCheck.setAdvice(checkDTO.getAdvice());
                afterIndentCommitCheck.setCreateTime(new Date());
                afterIndentCommitCheckService.getBaseMapper().updateById(afterIndentCommitCheck);


                //更新用户提交售后状态表
                afterIndentCommit.setCheckStatus(AfterIndentConde.PASS.getVal());
                afterIndentCommitService.getBaseMapper().updateById(afterIndentCommit);

               //插入审核记录表
               CheckAfterCommit checkAfterCommit = new CheckAfterCommit();
               checkAfterCommit.setAdvice(checkDTO.getAdvice());
               checkAfterCommit.setAfterSaleCommitId(afterIndentCommit.getId());
               checkAfterCommit.setAuditor(ShiroKit.getUserNotNull().getId());
               checkAfterCommit.setNode(AfterIndentConde.NODE2.getMessage());
               checkAfterCommit.setStatus(AfterIndentConde.PASS.getVal());
               checkAfterCommit.setTime(new Date());
               checkAfterCommitService.save(checkAfterCommit);
            }else {

                //更新用户提交售后状态表
                afterIndentCommit.setCheckStatus(AfterIndentConde.UNPASS.getVal());
                afterIndentCommitService.getBaseMapper().updateById(afterIndentCommit);

                //插入记录审核表
                CheckAfterCommit checkAfterCommit = new CheckAfterCommit();
                checkAfterCommit.setAdvice(checkDTO.getAdvice());
                checkAfterCommit.setAfterSaleCommitId(afterIndentCommit.getId());
                checkAfterCommit.setAuditor(ShiroKit.getUserNotNull().getId());
                checkAfterCommit.setNode(AfterIndentConde.NODE2.getMessage());
                checkAfterCommit.setStatus(AfterIndentConde.UNPASS.getVal());
                checkAfterCommit.setTime(new Date());
                checkAfterCommitService.save(checkAfterCommit);

                //删除本条审核记录
                afterIndentCommitCheckService.getBaseMapper().deleteById(checkDTO.getId());
            }
        }
    }

    /**
     * 审核提交售后信息表
     * @param checkDTO
     */
    public  void checkOrder(CheckDTO checkDTO){
        AfterIndentCheck afterIndentCheck = afterIndentCheckService.getById(checkDTO.getId());
        AfterIndentOrder afterIndentOrder = afterIndentOrderService.getById(afterIndentCheck.getAfterIndentOrderId());
        //插入到订单审核表
        CheckAfterIndent checkAfterIndent = new CheckAfterIndent();
        checkAfterIndent.setAfterSaleId(afterIndentOrder.getId());
        checkAfterIndent.setAdvice(checkDTO.getAdvice());
        checkAfterIndent.setAuditor(ShiroKit.getUserNotNull().getId());
        checkAfterIndent.setTime(new Date());
        checkAfterIndent.setNode(AfterIndentConde.NODE2.getMessage());
        if (checkDTO.getCode() == AfterIndentConde.PASS.getVal()){
            //更新用户售后审核表中的信息
            afterIndentOrder.setAfterStatus(AfterIndentConde.PASS.getVal());
            afterIndentOrderService.getBaseMapper().updateById(afterIndentOrder);

            //继续更新审核记录表中的数据
            checkAfterIndent.setStatus(AfterIndentConde.PASS.getVal());
        }else {
            //更新用户售后表中的信息
            afterIndentOrder.setAfterStatus(AfterIndentConde.UNPASS.getVal());
            afterIndentOrderService.getBaseMapper().updateById(afterIndentOrder);

            checkAfterIndent.setStatus(AfterIndentConde.UNPASS.getVal());
        }
        checkAfterIndentService.save(checkAfterIndent);
    }

    /**
     * 提交阶段退回
     * @param checkDTO
     */
    public void  returnCommit(CheckDTO checkDTO){

        AfterIndentCommitCheck afterIndentCheck = afterIndentCommitCheckService.getById(checkDTO.getId());
        AfterIndentCommit afterIndentCommit = afterIndentCommitService.getById(afterIndentCheck.getAfterIndentCommitId());

        //退回直接更改用户提交表的记录
        afterIndentCommit.setCheckStatus(AfterIndentConde.BACK.getVal());
        afterIndentCommitService.getBaseMapper().updateById(afterIndentCommit);

        //记录审核记录
        CheckAfterCommit checkAfterCommit = new CheckAfterCommit();
        checkAfterCommit.setTime(new Date());
        checkAfterCommit.setStatus(AfterIndentConde.BACK.getVal());
        checkAfterCommit.setNode(AfterIndentConde.NODE2.getMessage());
        checkAfterCommit.setAuditor(ShiroKit.getUserNotNull().getId());
        checkAfterCommit.setAdvice(checkDTO.getAdvice());
        checkAfterCommitService.save(checkAfterCommit);

        //更改审核表中的状态值
        afterIndentCheck.setStatus(AfterIndentConde.BACK.getVal());
        afterIndentCommitCheckService.getBaseMapper().updateById(afterIndentCheck);
    }


    /**
     * 提交售后审核信息阶段审核
     * @param checkDTO
     */
    public void returnCheckOrder(CheckDTO checkDTO){

        AfterIndentCheck afterIndentCheck = afterIndentCheckService.getById(checkDTO.getId());
        AfterIndentOrder afterIndentOrder = afterIndentOrderService.getById(afterIndentCheck.getAfterIndentOrderId());

        //售后订单退回
        afterIndentOrder.setAfterStatus(AfterIndentConde.BACK.getVal());
        afterIndentOrder.setTime(new Date());
        afterIndentOrderService.getBaseMapper().updateById(afterIndentOrder);

        //插入审核记录
        CheckAfterIndent checkAfterIndent = new CheckAfterIndent();
        checkAfterIndent.setNode(AfterIndentConde.NODE2.getMessage());
        checkAfterIndent.setStatus(AfterIndentConde.BACK.getVal());
        checkAfterIndent.setTime(new Date());
        checkAfterIndent.setAuditor(ShiroKit.getUserNotNull().getId());
        checkAfterIndent.setAdvice(checkDTO.getAdvice());
        checkAfterIndent.setAfterSaleId(afterIndentOrder.getId());
        checkAfterIndentService.save(checkAfterIndent);

        //更改审核表
        afterIndentCheck.setStatus(AfterIndentConde.BACK.getVal());
        afterIndentCheckService.getBaseMapper().updateById(afterIndentCheck);
    }
}
